'use strict';

angular.module('CBO').controller('TerminalListController', ['$scope', 'PublicModule', 'PublicEnum', 'PublicFunction', 'BaseService', '$location', 'Authentication',
    function($scope, PublicModule, PublicEnum, PublicFunction, BaseService, $location, Authentication) {
    	PublicModule.initModule($scope, 'Terminal');
        $scope.Module.Terminal.PageSize = 15;

        $scope.btnAdd = function(){
        	$location.url('/index/Terminal/Edit');
        };

        $scope.rowDblClick = function(){
            $scope.$apply(function(){
                $location.url("/index/Terminal/Edit/" + $scope.Module.Terminal.FocusedRecord._id);
            });
        };

        $scope.btnDelete = function(){
        	$scope.Module.Terminal.deleteSelecteds();
        };

        PublicModule.initModule($scope, '_WorkLocation');
        PublicModule.initModule($scope, 'StationTerminal');
        $scope.Module.StationTerminal.OrderBy = {WorkLocation: 1};
        $scope.Module.StationTerminal.Populate = {
            path: 'WorkLocation',
            select: 'Code Name Department',
            populate: {
                path: 'Department',
                select: 'Code Name',
                model: 'Department'
            }
        };

        $scope.btnFindWorkLocations = function(){
            if($scope.Module.Terminal.FocusedRecord != null){
                $scope.Module.StationTerminal.find(
                    {Terminal: $scope.Module.Terminal.FocusedRecord._id}, 
                    $scope.Module.StationTerminal.OrderBy,
                    $scope.Module.StationTerminal.Populate,
                    function(records){
                        $scope.Module._WorkLocation.Records = [];
                        for(var i=0; i<records.length; i++){
                            if(records[i].WorkLocation != null){
                                var newRecord = $scope.Module._WorkLocation.add();
                                newRecord.Code = records[i].WorkLocation.Code;
                                newRecord.Name = records[i].WorkLocation.Name;

                                if(records[i].WorkLocation.Department != null){
                                    newRecord.Department = records[i].WorkLocation.Department.Name;
                                }
                            }
                        }
                        $scope.Module._WorkLocation.emitOnLoadEvent();
                    }
                );
            }
        };
    }
]);